package cn.devpt.dev.base.config;

import java.sql.SQLIntegrityConstraintViolationException;

import javax.servlet.http.HttpServletRequest;

import cn.devpt.dev.base.bean.PtMsg;
import cn.devpt.dev.base.bean.PtRunTimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author ： wangxiaoliang
 * @Date: 2017年8月29日
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error";
    private static Logger log = LoggerFactory.getLogger(cn.devpt.dev.base.config.GlobalExceptionHandler.class);

    @ExceptionHandler(value = PtRunTimeException.class)
    @ResponseBody
    public PtMsg defaultErrorHandler(HttpServletRequest req, PtRunTimeException e) throws Exception {
        log.error(req.getRequestURI() + "============" + e.getMessage());
        return e.genMsg();
    }

    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    @ResponseBody
    public PtMsg defaultErrorHandler(HttpServletRequest req, SQLIntegrityConstraintViolationException e) throws Exception {
        log.error(req.getRequestURI() + "============" + e.getMessage());
        PtMsg code = new PtMsg();
        code.setCode("-1");
        code.setMessage(e.getMessage());
        return code;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public PtMsg defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        if (e.getCause() != null && e.getCause().getCause() instanceof PtRunTimeException) {// 在拦截器
            PtMsg result = new PtMsg();
            result.setCode("-1");
            result.setMessage(e.getCause().getCause().getMessage());
            return result;
        }
        log.error("异常捕获" + req.getRequestURI() + "============" + e.getMessage(), e);
        PtMsg result = new PtMsg();
        result.setCode("-1");
        //触发器是在第3层
        if (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause().getCause() != null) {
            result.setMessage(e.getCause().getCause().getCause().getMessage());
        } else {
            result.setMessage(e.getMessage());
        }
        return result;
    }
}